<!-- 考试记录 -->
<template>
  <div class="app-container">
    <!-- 搜索工具栏 -->
    <div class="toolbar">
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="试卷名称">
          <el-input
            v-model="queryParams.paperName"
            placeholder="试卷名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="科目">
          <el-input
            v-model="queryParams.subject"
            placeholder="科目"
            clearable
          />
        </el-form-item>
        <el-form-item label="考试时间">
          <el-date-picker
            v-model="queryParams.timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 考试记录列表 -->
    <el-table v-loading="loading" :data="recordList" style="width: 100%">
      <el-table-column
        prop="paperName"
        label="试卷名称"
        show-overflow-tooltip
      />
      <el-table-column prop="subject" label="科目" width="120" />
      <el-table-column prop="score" label="得分" width="100">
        <template #default="{ row }">
          <span :class="getScoreClass(row.score, row.totalScore)">
            {{ row.score }}/{{ row.totalScore }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="accuracy" label="正确率" width="100">
        <template #default="{ row }">
          <el-progress
            :percentage="(row.score / row.totalScore) * 100"
            :status="getProgressStatus(row.score, row.totalScore)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="duration" label="用时" width="120">
        <template #default="{ row }">
          {{ formatDuration(row.duration) }}
        </template>
      </el-table-column>
      <el-table-column prop="submitTime" label="提交时间" width="180">
        <template #default="{ row }">
          {{ formatDateTime(row.submitTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleViewDetail(row)">
            查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 统计卡片 -->
    <div class="statistics-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>考试次数</span>
              </div>
            </template>
            <div class="card-body">
              <div class="card-value">{{ statistics.totalExams }}</div>
              <div class="card-label">总考试次数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>平均分</span>
              </div>
            </template>
            <div class="card-body">
              <div class="card-value">
                {{ statistics.averageScore?.toFixed(1) }}
              </div>
              <div class="card-label">平均得分</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>最高分</span>
              </div>
            </template>
            <div class="card-body">
              <div class="card-value">{{ statistics.highestScore }}</div>
              <div class="card-label">最高得分</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>平均用时</span>
              </div>
            </template>
            <div class="card-body">
              <div class="card-value">
                {{ formatDuration(statistics.averageDuration) }}
              </div>
              <div class="card-label">平均答题时间</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 成绩趋势图 -->
    <div class="chart-container">
      <el-card shadow="hover">
        <template #header>
          <div class="card-header">
            <span>成绩趋势</span>
          </div>
        </template>
        <div class="chart" ref="scoreChartRef"></div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import { getExamRecords, getExamStatistics } from "@/api/exam";
import { formatDateTime } from "@/utils/format";
import * as echarts from "echarts";

const router = useRouter();

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  paperName: "",
  subject: "",
  timeRange: [],
});

// 列表数据
const loading = ref(false);
const recordList = ref([]);
const total = ref(0);
const statistics = reactive({
  totalExams: 0,
  averageScore: 0,
  highestScore: 0,
  averageDuration: 0,
});

// 图表实例
let scoreChart = null;
const scoreChartRef = ref(null);

// 获取考试记录列表
const getList = async () => {
  loading.value = true;
  try {
    const params = {
      ...queryParams,
      startTime: queryParams.timeRange?.[0],
      endTime: queryParams.timeRange?.[1],
    };
    delete params.timeRange;

    const { records, total: totalCount } = await getExamRecords(params);
    recordList.value = records;
    total.value = totalCount;
  } catch (error) {
    console.error("获取考试记录失败：", error);
  } finally {
    loading.value = false;
  }
};

// 获取统计数据
const getStatistics = async () => {
  try {
    const data = await getExamStatistics();
    Object.assign(statistics, data);
    initScoreChart(data.scoreHistory || []);
  } catch (error) {
    console.error("获取统计数据失败：", error);
  }
};

// 初始化成绩趋势图
const initScoreChart = (data) => {
  if (!scoreChartRef.value) return;

  const dates = data.map((item) => item.date);
  const scores = data.map((item) => item.score);

  scoreChart = echarts.init(scoreChartRef.value);
  scoreChart.setOption({
    tooltip: {
      trigger: "axis",
    },
    xAxis: {
      type: "category",
      data: dates,
      boundaryGap: false,
    },
    yAxis: {
      type: "value",
      name: "分数",
      min: 0,
      max: 100,
    },
    series: [
      {
        name: "得分",
        type: "line",
        data: scores,
        smooth: true,
        symbolSize: 8,
        itemStyle: {
          color: "#409EFF",
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: "rgba(64,158,255,0.3)",
            },
            {
              offset: 1,
              color: "rgba(64,158,255,0.1)",
            },
          ]),
        },
      },
    ],
  });
};

// 查询按钮点击
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

// 重置按钮点击
const resetQuery = () => {
  queryParams.paperName = "";
  queryParams.subject = "";
  queryParams.timeRange = [];
  handleQuery();
};

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.pageSize = val;
  getList();
};

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.pageNum = val;
  getList();
};

// 查看详情按钮点击
const handleViewDetail = (row) => {
  router.push(`/record/detail/${row.id}`);
};

// 格式化考试时长
const formatDuration = (duration) => {
  if (!duration) return "0分钟";
  if (duration < 60) {
    return `${duration}分钟`;
  }
  const hours = Math.floor(duration / 60);
  const minutes = duration % 60;
  return `${hours}小时${minutes}分钟`;
};

// 获取分数样式
const getScoreClass = (score, totalScore) => {
  const percentage = (score / totalScore) * 100;
  if (percentage >= 90) return "score-excellent";
  if (percentage >= 80) return "score-good";
  if (percentage >= 60) return "score-pass";
  return "score-fail";
};

// 获取进度条状态
const getProgressStatus = (score, totalScore) => {
  const percentage = (score / totalScore) * 100;
  if (percentage >= 90) return "success";
  if (percentage >= 60) return "";
  return "exception";
};

// 监听窗口大小变化
const handleResize = () => {
  scoreChart?.resize();
};

onMounted(() => {
  getList();
  getStatistics();
  window.addEventListener("resize", handleResize);
});

onUnmounted(() => {
  window.removeEventListener("resize", handleResize);
  scoreChart?.dispose();
});
</script>

<style scoped>
.toolbar {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.statistics-cards {
  margin: 20px 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-body {
  text-align: center;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.card-label {
  font-size: 14px;
  color: #909399;
}

.chart-container {
  margin-top: 20px;
}

.chart {
  height: 400px;
}

.score-excellent {
  color: #67c23a;
  font-weight: bold;
}

.score-good {
  color: #409eff;
  font-weight: bold;
}

.score-pass {
  color: #e6a23c;
  font-weight: bold;
}

.score-fail {
  color: #f56c6c;
  font-weight: bold;
}
</style>
